import React from 'react'
import 'braft-editor/dist/index.css'
import BraftEditor from 'braft-editor'
import 'braft-extensions/dist/table.css'
import Table from 'braft-extensions/dist/table'
import { Input } from "antd";

const options = {
  defaultColumns: 3, // 默认列数
  defaultRows: 3, // 默认行数
  withDropdown: true, // 插入表格前是否弹出下拉菜单
  exportAttrString: '', // 指定输出HTML时附加到table标签上的属性字符串
};

BraftEditor.use(Table(options));

// 编写扩展模块
const underdotExtension = {
  key: 'border-style',
  // 指定扩展类型
  type: 'inline-style',
  // 指定该扩展对哪些编辑器生效，不指定includeEditors则对所有编辑器生效
  includeEditors: ['demo-editor-with-underdot-ext'],
  // 指定扩展样式名，推荐使用全大写
  name: 'UNDERDOT',
  // 在编辑器工具栏中增加一个样式控制按钮，text可以为一个react组件
  control: {
    text: <span><img src='/ggeditor/border.png' width='16' /></span>,
  },
  // 指定该扩展样式的CSS规则，请注意，IE/EDGE浏览器暂时不支持textEmphasis
  style: {
    // textEmphasis: 'circle',
    // textEmphasisPosition: 'under',
    // WebkitTextEmphasis: 'circle',
    // WebkitTextEmphasisPosition: 'under',
    border: '1px solid #000000',
  },
  importer: (nodeName, node) => {
    // 指定html转换为editorState时，何种规则的内容将会附加上该扩展样式
    // 如果编辑器在createEditorState时使用的是RAW数据，并且开启了stripPastedStyles，则可以不指定importer，因为不存在html转editorState的场景
    return nodeName === 'span' && [].find.call(node.style, (styleName) => styleName.indexOf('border') !== -1)
  },
  exporter: () => {
    // 指定该样式在输出的html中如何呈现，对于inline-style类型的扩展可以不指定exporter，输出样式即为该扩展的style
    return (
      <span style={{
        // textEmphasis: 'circle',
        // textEmphasisPosition: 'under',
        // WebkitTextEmphasis: 'circle',
        // WebkitTextEmphasisPosition: 'under',
        border: '1px solid #000000',
      }} />
    )
  }
}

// 加载扩展模块
BraftEditor.use(underdotExtension)
// BraftEditor.use可以同时传入单个或多个扩展
// BraftEditor.use(ext) 或者 BraftEditor.use([ext1, ext2, [ext3, ext4]])都是合法的


export default class BraftEdit extends React.Component {

  state = {
    editorState: BraftEditor.createEditorState(), // 设置编辑器初始内容
    outputHTML: '<p></p>',
    inputTitle: '',
  };

  componentDidMount () {
    this.isLivinig = true
    // 加载文本标题
    setTimeout(this.setTitleAsync, 100);
    // 3秒后更改编辑器内容
    // setTimeout(this.setEditorContentAsync, 3000)
    setTimeout(this.setEditorContentAsync, 500)
  }

  componentWillUnmount () {
    this.isLivinig = false
  };

  handleChange = (editorState) => {
    this.setState({
      editorState: editorState,
      outputHTML: editorState.toHTML()
    })
  };

  setTitleAsync = () => {
    let bfContainer = document.getElementsByClassName('bf-container')[0];
    let bfContent = document.getElementsByClassName('bf-content')[0];
    var node = document.createElement("div");
    node.setAttribute("class", "bf-input");
    node.innerHTML = `
    <input
      style="
        height: 48px;
        width: 100%;
        border: 0px;
        font-size: 24px;
        font-weight: bold;
        outline: none;
        box-shadow: none;
        color: #000000cc;
        padding: 0 16px;
        border-bottom: 1px solid #d4d4d4;
      "
      class="bf-headerTitle"
      id="bf-headerTitle"
      value="${this.state.inputTitle}"
      placeholder="请输入标题"
    />`;
    node.children[0].onchange = e => {
      console.log(e.target.value);
      this.setState({ inputTitle: e.target.value });
      node.children[0].blur();
    };
    node.children[0].onkeydown = e => {
      // console.log(e.keyCode);
      if (e.keyCode === 13) {
        console.log(e.target.value);
        this.setState({
          inputTitle: e.target.value,
          editorState: BraftEditor.createEditorState('<p></p>'+this.state.editorState.toHTML())
        });
        node.children[0].blur();
      }
    };
    bfContainer.insertBefore(node, bfContent);
  }

  setEditorContentAsync = () => {
    const { content, title } = this.props;
    document.getElementById("bf-headerTitle").value = title;
    this.isLivinig && this.setState({
      inputTitle: title,
      editorState: BraftEditor.createEditorState(content)
    })
  };

  handleKeyCommand = (command) => {
    console.log(command);
  }

  render () {
    const { editorState, outputHTML } = this.state;

    return (
      <div>
        <div className="editor-wrapper" style={{ border: '1px solid #d4d4d4', height: '596px' }}>
          <BraftEditor
            value={editorState}
            placeholder="请输入正文"
            onChange={this.handleChange}
            controls={this.props.controls}
            extendControls={this.props.extendControls}
            excludeControls={this.props.excludeControls}
            id="demo-editor-with-underdot-ext"
            handleBeforeInput={(text, editorState) => {
              // console.log('text');
            }}
            handleKeyCommand={(e) => {
              console.log('handleKeyCommand', e);
            }}
            // 键盘按下响应，绑定按键
            keyBindingFn={(e) => {
              // console.log('keyBindingFn', e);
              // return azqsxw123
              (e);
            }}
          />
        </div>
        {/* <h5>输出内容</h5> */}
        {/* <div className="output-content">{outputHTML}</div> */}
      </div>
    )
  }
}
